package MyUtils;

import 其他.DataStructure.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 使用说明：
 *  TreeNode root = TreeUtils.deserialize("10,5,-3,3,2,null,11,3,-2,null,1");
 *
 *
 *  全是层序
 *      难点：null的处理
 */
public class TreeUtils {

    public static String treeToStr(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        sb.append(root.val + ",");
        while (!q.isEmpty()) {
            TreeNode cur = q.poll();
            if (cur.left != null) {
                q.add(cur.left);
                sb.append(cur.left.val + ",");
            } else if (cur.left == null) {
                sb.append("null,");
            }

            if (cur.right != null) {
                q.add(cur.right);
                sb.append(cur.right.val + ",");
            } else if (cur.right == null) {
                sb.append("null,");
            }
        }
        return sb.toString();
    }

    public static TreeNode strToTree(String data) {
        String[] s = data.split(",");
        TreeNode headRoot = new TreeNode(Integer.parseInt(s[0]));
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(headRoot);
        int curInd = 0;
        int step = 0;
        while (!q.isEmpty()) {
            int oldSize = q.size();
            for (int i = 0; i < oldSize; i++) {
                TreeNode cur = q.poll();
                int curIndTmp = curInd;
                if (cur == null) {
                    continue;
                }
                if (curIndTmp + 1 < s.length) {
                    if (s[curIndTmp + 1].equals("null")) {
                        cur.left = null;
                        q.add(null);
                    } else {
                        cur.left = new TreeNode(Integer.parseInt(s[curIndTmp + 1]));
                        q.add(cur.left);
                    }
                    curInd++;
                }
                if (curIndTmp + 2 < s.length) {
                    if (s[curIndTmp + 2].equals("null")) {
                        cur.right = null;
                        q.add(null);
                    } else {
                        cur.right = new TreeNode(Integer.parseInt(s[curIndTmp + 2]));
                        q.add(cur.right);
                    }
                    curInd++;
                }
            }
            step++;
        }
        return headRoot;
    }
}
